<?php
	require '../include/library.inc.php';
	require '../include/admin_login.inc.php';
	
# Ако запазваме	
if ($_POST['is_submitted']) {
    $error_message = '';
    
	# Проверки
	if (!$_POST['name'])  $error_message .= 'School Name is required<br/>';
	
	if (!$_POST['sef_url'])  $error_message .= 'SEF URL is required<br/>';
	elseif(!preg_match('/^[0-9A-Za-z\-\_]+$/', $_POST['sef_url'])) $error_message .= 'SEF URL is invalid<br/>';
	
	$sql = "SELECT
				school_id
			FROM
				schools
			WHERE
				sef_url = '".$_POST['sef_url']."'
			  ";
	$result = query($sql);
	if ($row_seo = mysql_fetch_object($result)) $error_message .= 'The SEF URL already used by another school<br/>';
	
	if (!$_POST['description'])  $error_message .= 'Description is required<br/>';
	if (!$_POST['city_id'])  $error_message .= 'City is required<br/>';
	if (!$_POST['terms'])  $error_message .= 'Terms & Conditions are required<br/>';
    
	# OK
    if(!$error_message) {
		
		$sql = 'SELECT MAX(order_number)+1 AS order_number FROM schools';
		$row_number = mysql_fetch_assoc(query($sql));
		
		# Create the school
		$sql = 'INSERT INTO schools
				  (name, sef_url, description, meta_description, terms, city_id, address, lat, lng, published, order_number)
				VALUES
				  (\''.escape($_POST['name']).'\', \''.escape($_POST['sef_url']).'\', \''.escape($_POST['description']).'\', \''.escape($_POST['meta_description']).'\', \''.escape($_POST['terms']).'\', '.intval($_POST['city_id']).', \''.escape($_POST['address']).'\', \''.floatval($_POST['lat']).'\', \''.floatval($_POST['lng']).'\', '.intval($_POST['published']).', \''.$row_number['order_number'].'\')
				  ';
		query($sql);
		$school_id = mysql_insert_id();
		
		
		# Images
		for($i=1;$i<4;$i++){
			if (is_uploaded_file($_FILES['image_'.$i]['tmp_name'])) {
				
				$upload_path = "../uploads/img/";
				
				$tmp_file = $_FILES['image_'.$i]['tmp_name'];
				$exp = explode('.',$_FILES['image_'.$i]['name']);
				$img_type = strtolower(end($exp));
				
				$sql = 'INSERT INTO images
							(school_id)
						VALUES
							('.$school_id.')
				';
				query($sql);
				$image_id = mysql_insert_id();
				
				if(copy($tmp_file, $upload_path.'img_'.$_POST['sef_url'].'_'.$image_id.'.'.$img_type)) {
					
					$sql = 'UPDATE images
							SET
								filename = \''.'img_'.$_POST['sef_url'].'_'.$image_id.'.'.$img_type.'\'
							WHERE
								image_id = '.$image_id.'
							  ';
					query($sql);
					
				} else{
					
					$sql = 'DELETE FROM 
							   images
							WHERE
							   image_id = '.$image_id.'
							 ';
					query($sql);
					$_SESSION['message'] .= 'Upload error for image '.$i.'. ';
					
				}
			}
		}
		
	  
	  	# Качване на logo
		if (is_uploaded_file($_FILES['logo']['tmp_name'])) {
			
			$upload_path = "../uploads/logos/";
			
			$tmp_file = $_FILES['logo']['tmp_name'];
			$exp = explode('.',$_FILES['logo']['name']);
			$img_type = strtolower(end($exp));
			
			$new_name = 'school_'.$school_id.'_logo.'.$img_type;
			
			if(copy($tmp_file, $upload_path.$new_name)) {
				
				$sql = 'UPDATE schools
						SET
							logo = \''.$new_name.'\'
						WHERE
							school_id = '.$school_id.'
				';
				query($sql);
				
			} else{
				
				$_SESSION['message'] .= 'The logo was not uploaded!';
				
			}
		}
			
      
		$_SESSION['message'] = 'New school was created!';
		redirect("schools.php");
	  
    }
   
}

head_admin("Create New School");
?>
<script type="text/javascript" src="<?=HTML_BASE_ADMIN?>tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
	// General options
	mode : "exact",
    elements : "description, terms",
	theme : "advanced",
	relative_urls : false,
	plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager",

	// Theme options
	theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
	theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
	theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,image,insertimage",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resizing : false,

	// Drop lists for link/image/media/template dialogs
	//template_external_list_url : "js/template_list.js",
	external_link_list_url : "js/link_list.php",
	//media_external_list_url : "js/media_list.js",
	//external_image_list_url : "js/image_list.php"
	
});
</script>
		
		<?php if ($error_message) { ?>
		  <div class="message red">
			<h4>Error!</h4>
			<?=$error_message?>
		  </div>
		<?php } ?>
		
		
		
            <div class="topbuttons">
            	<a href="schools.php">Back to schools</a>
            </div>
            
            <h3>Create New School</h3>
            
            <form action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">
            <input type="hidden" name="is_submitted" value="1" />
            
			<dl class="clearfix">
			
			<dt><label class="required">School Name</label></dt>
            <dd><input class="inputbox w500" name="name" type="text" value="<?=sth($_POST['name'])?>" ></dd>            
			
			<dt><label class="required">SEF URL (Search Engine Friendly link. For Example: name-of-the-school)</label></dt>
            <dd><?=HTML_BASE?>school/<input class="inputbox w250" name="sef_url" type="text" value="<?=$_POST['sef_url']?>" ></dd>
			
            <dt><label class="required">Description</label></dt>
            <dd><textarea id="description" name="description" rows="24" style="width:100%" ><?=sth($_POST['description'])?></textarea></dd>
			
			<dt><label>Meta description</label></dt>
            <dd><textarea class="inputbox w500" name="meta_description" rows="3"><?=sth($_POST['meta_description'])?></textarea></dd>
            
            <dt><label class="required">Terms &amp; Conditions</label></dt>
            <dd><textarea id="terms" name="terms" rows="16" style="width:100%" ><?=sth($_POST['terms'])?></textarea></dd>
            
            </dl>
            
            
            
            <h4>Location</h4>
            <dl>
            
            <dt><label class="required">City</label></dt>
			<dd><select class="inputbox w250" name="city_id">
            <option value="">Choose city</option>
            <?php
			$sql = "SELECT
						ci.city_id,
						ci.name AS city,
						co.name AS country
					FROM
						cities AS ci,
						countries AS co
					WHERE
						ci.country_id = co.country_id
					ORDER BY
						ci.country_id
					  ";
			$result = query($sql);
            while ($row_city = mysql_fetch_object($result)) {
				echo '<option value="'.$row_city->city_id.'" '.(($_POST['city_id']==$row_city->city_id)?' selected':'').'>'.$row_city->city.', '.$row_city->country.'</option>';
			}
			?>
            </select></dd>
            
            <dt><label>Street Address</label></dt>
            <dd><textarea class="inputbox w500" name="address" rows="2"><?=sth($_POST['address'])?></textarea></dd>
            
            <dt><label>Coordinates</label></dt>
            <dd>
            <input class="inputbox" style="width:120px;" id="lat" name="lat" type="text" value="<?=$_POST['lat']?>" maxlength="20" />
            <input class="inputbox" style="width:120px;" id="lng" name="lng" type="text" value="<?=$_POST['lng']?>" maxlength="20" />
            </dd>
            
            </dl>
            
            <h4>Images (300x250px)</h4>
            
            <dl>
            
            <dt><label>Image 1</label></dt>
            <dd><input class="inputbox w500" name="image_1" type="file" /></dd>
			
			<dt><label>Image 2</label></dt>
            <dd><input class="inputbox w500" name="image_2" type="file" /></dd>
			
			<dt><label>Image 3</label></dt>
            <dd><input class="inputbox w500" name="image_3" type="file" /></dd>
            
            </dl>
            
            <dl>
            
            <dt><label>School Logo (height: 100px)</label></dt>
            <dd><input class="inputbox w500" name="logo" type="file" /></dd>
            
            
            <dd><label>
			<input class="checkbox" name="published" id="published" type="checkbox" value="1" <?=(($_POST['published'])?"checked=\"checked\"":"")?> />
			Published</label></dd>
            
                        
			<dd class="submit">
            <input type="submit" name="submit" id="submit" value="Create The School">
            </dd>
			
            </dl>
            
            <h4>Courses</h4>
            <dl>
            You have to create the school first.
            </dl>
            
            
			</form>
            
<?php
	foot_admin(); 
?>